package com.yun.util.yun.Id;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;


@Service
public class PrimaryKeyUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @param date
     * @return
     */
    public String getOrderIdPrefix(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        String monthFormat = String.format("%1$02d", month+1);
        String dayFormat = String.format("%1$02d", day);
        String hourFormat = String.format("%1$02d", hour);

        return year + monthFormat + dayFormat+hourFormat;
    }

    public Long orderId(String prefix) {
        String key = "ORDER_ID_" + prefix;
        String orderId = null;
        try {
            Long increment = redisTemplate.opsForValue().increment(key,1);
            //往前补6位
            orderId=prefix+String.format("%1$06d",increment);
        } catch (Exception e) {
            System.out.println("生成单号失败");
            e.printStackTrace();
        }
        return Long.valueOf(orderId);
    }

    public static void main(String[] args) {
        PrimaryKeyUtil primaryKeyUtil = new PrimaryKeyUtil();
        long startMillis = System.currentTimeMillis();
        String orderIdPrefix = primaryKeyUtil.getOrderIdPrefix(new Date());
        for (int i = 0; i < 1000; i++) {
            Long aLong = primaryKeyUtil.orderId(orderIdPrefix);
            System.out.println(aLong);
        }
        long endMillis = System.currentTimeMillis();
        System.out.println("测试生成1000个使用时间："+(endMillis-startMillis)+",单位毫秒");


    }







}

